package com.song.splitwords;

import java.util.ArrayList;
import java.util.List;

//正向最大匹配 中文分词
public class SplitWords {

    private static String[] DICS = {"中文", "中华", "中华人民", "共和国", "万岁", "人民", "共和", "国"};
    private List<String> list = new ArrayList<>();
    private static int MAX_LENGTH = 4;

    //模拟词库
    public void DICSToMap(){
        list.add("中文");
        list.add("中华");
        list.add("中华人民");
        list.add("共和国");
        list.add("万岁");
        list.add("人民");
        list.add("共和");
        list.add("国");
    }
    //正向最大匹配
    public List<String> FMM(String text1) {
        List<String> backList = new ArrayList<>();
        int i = 0, j = 0;
        int len_text = text1.length();

        while (i < len_text) {
            int end = i + MAX_LENGTH;
            if (end >= text1.length()) {
                end = text1.length();
            }
            String substring = text1.substring(i, end);  //截取最大长度的子串
            for (j = substring.length(); j > 0; j--) {
                //j==1 代表截取的字符串只有一个字符,截取结束退出
                if (j == 1) {
                    // backList.add(""+substring.charAt(0));
                    break;
                }
                String str = substring.substring(0, j);
                    if (list.contains(str)) {
                        backList.add(str);
                        i = i + str.length() - 1;
                        break;
                    }
            }
            if (j == 1) {
                backList.add(""+substring.charAt(0));
                break;
            }
            i = i + 1;
        }
        return backList;
    }

    //逆向最大匹配 算法

    public List<String> BMM(String string){
        List<String> backList = new ArrayList<>();



        return backList ;
    }

    public static void main(String[] args) {
        SplitWords sw = new SplitWords();
        String str = "中华人民共和国万岁";
        sw.DICSToMap();
        List<String> fmm = sw.FMM(str);
        System.out.println(fmm.toString());
    }


}
